代码之家  ›  专栏  ›  技术社区  ›  for_stack

带有模板专门化的标记分派

c++
  •  1
  • for_stack  · 技术社区  · 7 年前

    分派专用标记是否有效?下面的代码可以编译并运行,没有任何错误。但我仍然想确认这样做是否有效。

    template <typename T, typename = void>
    struct tag {};
    
    // Specialize the tag
    template <typename T>
    struct tag<T, typename std::enable_if<std::is_arithmetic<T>::value>::type> {};
    
    template <typename T>
    T func(int i) {
        return real_func(tag<T>(), i);
    }
    
    string real_func(tag<string>, int i) {
        return to_string(i);
    }
    
    template <typename T>
    T real_func(tag<T,  // <--------- Is this valid?
                    typename std::enable_if<std::is_arithmetic<T>::value>::type>,
                int i) {
        return static_cast<T>(i);
    }
    

    还有,有没有其他方法可以达到同样的目标?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Jarod42    7 年前

    你的专用标签没有带来任何有用的东西。如果您以一种奇怪的方式使用SFINAE,只需执行以下操作:

    template <typename T> struct tag{};
    
    std::string real_func(tag<std::string>, int i) {
        return to_string(i);
    }
    
    template <typename T, typename std::enable_if<std::is_arithmetic<T>::value, int>::type = 0>
    T real_func(tag<T>, int i) {
        return static_cast<T>(i);
    }
    
    template <typename T>
    T func(int i) {
        return real_func(tag<T>(), i);
    }