如何强制使用模板专业化?

drw*_*owe 13 c++ template-specialization

我试图让我的模板函数产生编译时错误,如果实例化非专用基本版本.我尝试了通常的编译时断言模式(负数组大小),但即使没有实例化模板,编译也会失败.当且仅当基础模板函数被实例化时,有关如何使其失败的任何想法?

template<class Foo> void func(Foo x) {
  // I want the compiler to complain only if this function is instantiated.
  // Instead, the compiler is complaining here at the declaration.
  int Must_Use_Specialization[-1];
}

template<> void func(int x) {
  printf("Hi\n");
}
Run Code Online (Sandbox Code Playgroud)

Pub*_*bby 19

不定义它是最简单的解决方案:

template<class Foo> void func(Foo x);

template<> void func(int x) {
  printf("Hi\n");
}
Run Code Online (Sandbox Code Playgroud)

您也可以在CPP文件中定义它们并使用它可以工作.

和静态断言方法:

template<class Foo> void func(Foo x) {
  static_assert(sizeof(Foo) != sizeof(Foo), "func must be specialized for this type!");
}
Run Code Online (Sandbox Code Playgroud)

  • 我将消息更改为"func必须专门用于此类型!"`以便澄清 (2认同)

Gri*_*zly 7

在C++ 11中,您可以这样使用static_assert:

template<typename T> struct fake_dependency: public std::false_type {};
template<class Foo> void func(Foo x) {
   static_assert(fake_dependency<Foo>::value, "must use specialization");
}
Run Code Online (Sandbox Code Playgroud)

fake_dependency结构是必要的,以使断言依赖于你的模板参数,因此它与评价等待,直到模板实例.您可以像这样修复您的解决方案:

template<class> struct fake_dependency { enum {value = -1 }; };

template<class Foo> void func(Foo x) {
    int Must_Use_Specialization[fake_dependency<Foo>::value];
}
Run Code Online (Sandbox Code Playgroud)

另见这里的现场演示.


jpa*_*cek 5

你必须依赖它Foo,像这样:

int Must_Use_Specialization[-sizeof(Foo)];
Run Code Online (Sandbox Code Playgroud)


Use*_*ess 1

只需使用Boost.StaticAssert

(编辑:或者static_assert如果你有 C++11 支持。我忘了这一点)。