繁体   English   中英

为什么在匿名名称空间中定义模板时内部链接错误?

[英]Why internal linkage error when template defined in anonymous namespace?

在匿名名称空间中声明模板会导致错误error: function '(anonymous namespace)::f<std::__1::vector<float, std::__1::allocator<float> > >' has internal linkage but is not defined

这些代码如下:

    #include <type_traits>
    #include <vector>

    namespace {

    template <class T>
    void f(const T& data);

    template <>
    void f<int>(const int& data){}

    template <typename Iterable, typename std::decay<decltype(*std::begin(std::declval<Iterable>()))>::type>
    void f(const Iterable& data) {
        ;
    }

    }

    void g() {
        std::vector<float> x;
        f(x);
    }

我搜索发现“ 可能相同” ,但没有解释。

更新:
如果删除匿名命名空间,则错误将变为Undefined symbols for void f<std::__1::vector<float, std::__1::allocator<float> > >(std::__1::vector<float, std::__1::allocator<float> > const&

您有两个重载的模板函数f ,第二个函数具有两个模板参数。 f(x); 将调用void f(const T& data); 确实在任何地方都没有定义。

现在,我将草拟一个简短的解决方案。

最实用的方法是使用部分专用的帮助程序类,因为模板功能不能部分专用。

#include <type_traits>
#include <vector>
#include <iostream>

namespace {

    template<typename T, typename=void>
    struct ff;

    template<>
    struct ff<int, void> {

        static constexpr bool specialized=true;
        static inline void func(const int &data)
        {
            std::cout << "int" << std::endl;
        }
    };

    template<typename T>
    struct ff<T,
         std::void_t<decltype(*std::begin(std::declval<T>()))>> {

        static constexpr bool specialized=true;
        static inline void func(const T &data)
        {
            std::cout << "vector" << std::endl;
        }
    };

    template <class T, typename=decltype(ff<T>::specialized)>
    inline void f(const T& data)
    {
        ff<T>::func(data);
    }
}

int main()
{
    std::vector<float> x;
    int y;
    f(x); // Result: vector
    f(y); // Result: int

    // Error:
    //
    // char *z;
    // f(z);
}

出于SFINAE的目的,您仍然需要模板函数上的第二个模板参数,并且大多数编译器应在适度的优化级别上优化掉多余的函数调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM