在函数模板特化中覆盖返回类型

时间:2013-04-09 20:30:43

标签: c++ templates

我想专门化一个函数模板,以便返回类型根据模板参数的类型而改变。

class ReturnTypeSpecialization
{
public:
    template<typename T>
    T Item();
};

// Normally just return the template type
template<typename T>
T ReturnTypeSpecialization::Item() { ... }

// When a float is specified, return an int
// This doesn't work:
template<float>
int ReturnTypeSpecialization::Item() { ... }

这可能吗?我不能使用C ++ 11。

5 个答案:

答案 0 :(得分:45)

由于专业化必须与返回类型的基本模板一致,您可以通过添加“返回类型特征”,可以专门化的结构并从中绘制真实的返回类型来实现:

// in the normal case, just the identity
template<class T>
struct item_return{ typedef T type; };

template<class T>
typename item_return<T>::type item();

template<>
struct item_return<float>{ typedef int type; };
template<>
int item<float>();

Live example.

请注意,您可能希望坚持以下内容,因此您只需要更新item_return专业化中的返回类型。

template<>
item_return<float>::type foo<float>(){ ... }
// note: No `typename` needed, because `float` is not a dependent type

答案 1 :(得分:5)

也许您可以使用以下黑客攻击。鉴于这些简单的类型特征:

template<bool b, typename T, typename U>
struct conditional { typedef T type; };

template<typename T, typename U>
struct conditional<false, T, U> { typedef U type; };

template<typename T, typename U>
struct is_same { static const bool value = false; };

template<typename T>
struct is_same<T, T> { static const bool value = true; };

您可以按如下方式编写您的类和专用成员函数:

class ReturnTypeSpecialization
{
public:
    template<typename T>
    typename conditional<is_same<T, float>::value, int, T>::type 
    Item();
};

// Normally just return the template type
template<typename T>
typename conditional<is_same<T, float>::value, int, T>::type
ReturnTypeSpecialization::Item() { return T(); }

// When a float is specified, return an int
template<>
int ReturnTypeSpecialization::Item<float>() { return 1.0f; }

简单的测试程序(仅用于验证的C ++ 11):

int main()
{
    ReturnTypeSpecialization obj;
    static_assert(std::is_same<decltype(obj.Item<bool>()), bool>::value, "!");
    static_assert(std::is_same<decltype(obj.Item<float>()), int>::value, "!");
}

这是live example

答案 2 :(得分:5)

执行一个worker类中的所有特化,并使用一个简单的函数作为隐式专用的包装器。

#include <iostream>
using std::cout;

// worker class -- return a reference to the given value
template< typename V > struct worker
   {
   typedef V const & type;
   static type get( V const & v ) { return v; }
   };

// worker class specialization -- convert 'unsigned char' to 'int'
template<> struct worker<unsigned char>
   {
   typedef int type;
   static type get( unsigned char const & v ) { return v; }
   };

// mapper function
template< typename V > typename worker<V>::type mapper( V const & v )
   {
   return worker<V>::get(v);
   }

int main()
   {
   char a='A';
   unsigned char b='B';
   cout << "a=" << mapper(a) << ", b=" << mapper(b) << "\n";
   }

在此示例中,unsigned char的特化使其转换为int,以便cout将其显示为数字而不是字符,从而生成以下输出...

a=A, b=66

答案 3 :(得分:4)

你可以这样做模板专业化:

template<typename T>
T item() {
    return T();
}

template<>
float item<float>() {
    return 1.0f;
}

答案 4 :(得分:0)

嗨,我尝试使用模板特化来返回基元的参数值以及 std::string 数据,同时我遇到了很多未解决的外部重定义错误。 因此,如果有人遇到这样的情况,他/她可以在想要返回不同的数据类型(包括字符串)时使用以下内容, 注意:模板函数必须是头文件(*.h)的一部分... 所以我们在这里使用模板特化字符串数据类型...... 在类内部作为内联成员,我们必须使用模板 specialize 方法,并且在同一个文件中我们也可以定义模板。

class ConfigFileParser
{
public:
    bool ParseConfigFile(const std::string& file_name);
    template <typename T>
    T GetParameterValue(const std::string key);
    template <>
    std::string GetParameterValue<std::string>(const std::string key)
    {
        std::string param_val = "";
        //do logical operation here... 
        return param_val;
    }
private:
    // private functions...

    // private data...
};

template <typename T>
T ConfigFileParser::GetParameterValue(const std::string key)
{
    T param_val = 0;
    std::stringstream ss;
    std::string val_str;
    // do some operation here...
    ss << val_str.c_str();
    ss >> param_val;

    return param_val;
}
相关问题