相关疑难解决方法(0)

如何防止非专业模板实例化?

我有一个模板化class(称之为Foo),它有几个特化.如果有人试图使用非专业版本,我希望编译失败Foo.

这是我实际拥有的:

template <typename Type>
class Foo
{
  Foo() { cannot_instantiate_an_unspecialized_Foo(); }

  // This method is NEVER defined to prevent linking.
  // Its name was chosen to provide a clear explanation why the compilation failed.
  void cannot_instantiate_an_unspecialized_Foo();
};

template <>
class Foo<int>
{    };

template <>
class Foo<double>
{    };
Run Code Online (Sandbox Code Playgroud)

以便:

int main()
{
  Foo<int> foo;
}
Run Code Online (Sandbox Code Playgroud)

适用时:

int main()
{
  Foo<char> foo;
}
Run Code Online (Sandbox Code Playgroud)

才不是.

显然,编译器链只在链接过程发生时才会抱怨.但有没有办法让它在之前抱怨?

我可以用boost.

c++ templates boost compilation

38
推荐指数
3
解决办法
5090
查看次数

标签 统计

boost ×1

c++ ×1

compilation ×1

templates ×1