【发布时间】:2019-06-04 13:55:40
【问题描述】:
我有一个模板方法foo。我想有几个不同的实现:T、vector<T> 和vector<vector<T>> 其中T 是一个内置类型或一些复杂的类。我想使用 SFINAE 来分离内置类型和类的实现,并限制一组允许的类型。
以下代码可以正常工作,但我收到警告消息:
8:37: warning: inline function 'constexpr bool isType() [with T =
std::vector<int>]' used but never defined
8:37: warning: inline function 'constexpr bool isType() [with T =
std::vector<std::vector<int> >]' used but never defined
#include <type_traits>
#include <vector>
using namespace std;
class ComplexClass{};
template<typename T> constexpr bool isType();
template<> constexpr bool isType<int>() {return true;}
template<> constexpr bool isType<ComplexClass>() {return false;}
template <typename T>
inline typename enable_if<isType<T>(), void>::type
foo(T& value) {}
template <typename T>
inline typename enable_if<!isType<T>(), void>::type
foo(T& value) {}
template <typename T>
inline typename enable_if<isType<T>(), void>::type
foo(vector<T>& value) {}
template <typename T>
inline typename enable_if<isType<T>(), void>::type
foo(vector<vector<T>>& value) {}
int main()
{
int a;
vector<int> b;
vector<vector<int>> c;
ComplexClass d;
char e;
foo(a);
foo(b);
foo(c);
foo(d);
// foo(e); // has to lead to an error
return 0;
}
看起来编译器试图将vector<...> 传递给第一个enable_if 方法但失败了。但是最好跳过这些方法,因为我们有更好的 vector<T> 和 vector<vector<T>> 候选者。有可能吗?
【问题讨论】:
-
我会选择部分专业化(并将函数放入类中)。比 SFINAE 容易得多。
-
如果我理解正确,这是不是:wandbox.org/permlink/eRVkR4R58ezSAWhL 不是你想要的?忽略警告。
标签: c++ c++11 templates sfinae enable-if