我有一个模板方法,它有两个专门的版本,分别是bool和vector<string>。
基本版本:
template <class T>
const T InternGetValue(const std::string& pfad) const
{
...
}专用版本:
template <>
const bool InternGetValue(const std::string& pfad) const
{
...
}
template <>
const std::vector<std::string> InternGetValue< std::vector<std::string>>(const std::string& pfad) const
{
...
}现在,我想实现一个专门化,它将接受所有类型的vector<aritmethic_data_type>,如vector<double>、vector<int>或vector<float>。
我可以通过为上述类型编写重载来实现这一点,但我有兴趣通过另一个专门化来实现我的目标。
这就是我到目前为止尝试过的(导致错误“非法使用显式模板参数”):
template <class T>
const std::vector<T> InternGetValue< std::vector<T>>(const std::string& pfad, typename boost::enable_if<boost::is_arithmetic<T>>::type* dummy = 0) const
{
}发布于 2011-09-29 09:36:06
我认为std::enable_if和std::is_integral一起可以解决这个问题:
template<typename T>
std::vector<typename std::enable_if<std::is_integral<T>::value, T>::type>
f(const std::string& d);如果std::没有它们,那么如果可以的话使用boost::。它有他们。
发布于 2011-09-29 13:19:36
好吧,很复杂,但我把一切都做好了。我不能只检查第一个(默认)函数重载中的is_integral类型,因为这会导致SFINAE删除非向量的重载。
与Nawaz的解决方案不同,这不需要添加虚拟参数,但它确实需要默认函数模板上的enable_if条件。
这在VS2010上是可行的。
#include <vector>
#include <string>
#include <type_traits>
using namespace std;
template <typename T> struct is_vector { static const bool value = false; };
template <typename T> struct is_vector< std::vector<T> > { static const bool value = true; };
// metafunction to extract what type a vector is specialised on
// vector_type<vector<T>>::type == T
template <class T>
struct vector_type
{
private:
template <class T>
struct ident
{
typedef T type;
};
template <class C>
static ident<C> test(vector<C>);
static ident<void> test(...);
typedef decltype(test(T())) vec_type;
public:
typedef typename vec_type::type type;
};
// default version
template <class T>
const typename enable_if<!is_vector<T>::value || !is_integral<typename vector_type<T>::type>::value, T>::type
InternGetValue(const std::string& pfad)
{
return T();
}
// bool specialisation
template <>
const bool
InternGetValue<bool>(const std::string& pfad)
{
return true;
}
// vector<string> specialisation
template <>
const vector<string>
InternGetValue<vector<string>>(const std::string& pfad)
{
return vector<string>();
}
// vector<T> specialisation (where T is integral)
template <class T>
const typename enable_if<is_vector<T>::value && is_integral<typename vector_type<T>::type>::value, T>::type
InternGetValue(const std::string& pfad)
{
return T();
}
int main()
{
string x;
auto a = InternGetValue<int>(x);
auto b = InternGetValue<bool>(x);
auto c = InternGetValue<vector<string>>(x);
auto d = InternGetValue<vector<pair<int, int>>>(x);
auto e = InternGetValue<vector<int>>(x);
}https://stackoverflow.com/questions/7595243
复制相似问题