Title: How to limit instantialization?

For a template class:
template <typename T>
struct X
{
    static void f(){...}

};

Is there any way to prevent this class from being instantialized for
different T?
e.g:
X<int>::f();
X<int>::f() //ok
///
X<int>::f();
X<double>::f() //compiling error
Instantialization may be found in different source files, and X<T> may
not have to have any instance.
I tried some methods, but failed to prevent it in compile time.
Can anyone help me out?
(1)
On 12 Mrz., 15:19, "shifan3" <shifan1234...@163.com> wrote:
SFINAE is your friend. Your main task is to define/specialize
your traits class MyTraits, which specifies enablement, properly.
In this case I have used explicit specializiation for it, maybe you
need partial specialization:
template <bool Enable, typename T = void>
struct EnableIf {
   typedef T Type;

};
template <typename T>
struct EnableIf<false, T> {

};
template <typename T>
struct MyTraits {
   static const bool value = false; // Default case: Disable

};
template <>
struct MyTraits<int> {
   static const bool value = true;

};
template <typename T>
struct X
{
     static typename
     EnableIf<MyTraits<T>::value>::Type f(){...}

};
int main() {
   X<int>::f(); // OK
   X<double>::f(); // Fails

}
Greetings from Bremen,
Daniel Krügler

(2)
template <typename T>
struct X
{
    static void f(){...}

};
template<> struct X<double>;
or, if you don't want the incomplete type,
template<>
struct X<double>
{

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值