【发布时间】:2014-06-16 15:57:21
【问题描述】:
如果用户尝试使用给定的模板参数调用该函数,如何专门化模板函数以在编译时生成错误?
通过使用以下成语,我能够为模板 class 获得这种行为...
template <typename T>
class MyClass< std::vector<T> >;
我要修改的函数的基本签名是...
template <typename T>
T bar(const int arg) const {
...
}
如果我使用与禁止某些模板类相同的范式...
template<>
std::string foo::bar(const int arg) const;
我可以生成链接器错误,我认为这比运行时错误更可取,但仍然不是我想要的。
由于我无法使用 C++11,我无法使用 static_assert,如 here 所述。相反,我正在尝试像这样使用BOOST_STATIC_ASSERT...
template<>
std::string foo::bar(const int arg) const {
BOOST_STATIC_ASSERT(false);
return "";
}
但是,这会产生以下编译时错误,即使我不尝试使用我试图禁止的模板参数调用函数的实例...
error: invalid application of 'sizeof' to incomplete type 'boost::STATIC_ASSERTION_FAILURE<false>'
我找到了this post,但它并没有真正提供我认为适用于我的任何见解。有人可以帮忙吗?
【问题讨论】:
-
嗯,也许你可以用这个link
-
函数模板的显式特化就像一个简单的函数,所以任何静态断言都会触发。
-
@Sumsar1812,你指的是哪个链接?
-
这就是你的建议...
BOOST_STATIC_ASSERT(typeid(std::string) != typeid(T));这会引发编译器错误...error: 'typeid' operator cannot appear in a constant-expression -
什么是
foo?一个命名空间,一个类?
标签: c++ templates boost static-assert