繁体   English   中英

未定义对类模板的静态变量的引用

[英]Undefined reference to static variable of a class template

下面是我的代码:

// types.h
template <typename T>
struct type_to_char {};

template <>
struct type_to_char<char> {
  static constexpr char str[] = "baz";
};


// main.cpp
#include <iostream>
#include <string>

#include "types.h"

int main() {
  std::cout << type_to_char<char>::str << std::endl;
    return 0;
}

尝试编译时,链接器返回错误: undefined reference to type_to_char<char>::str

我遇到了这个答案 ,但是由于模板未编译,因此我不确定如何在我的情况下应用它。 我应该在项目中放置一个单独的.cpp文件吗?

constexpr变量的声明和定义之间有什么区别? 没有初始化程序就无法声明这样的变量,那么为什么要在.cpp文件中放置一个单独的定义?

我希望对此进行一些澄清

由于您完全专注于一个类,因此在许多方面它的行为都类似于未模板化的类。 一个例子是,它的静态成员必须像非模板类一样在实现文件中实例化。

// header file (type.h)
template <typename T>
struct type_to_char {};

template <>
struct type_to_char<char> {
  static constexpr char str[] = "baz";
};

// impementation file (type.cpp)
constexpr char type_to_char <char>::str[];

// main.cpp
#include <iostream>
#include <type.h>

int main() {
    std::cout << type_to_char<char>::str << std::endl;
    return 0;
}

您需要在最终程序中链接的.cpp中提供定义。 例如:

   // types.h
    template <typename T>
    struct type_to_char {};

    template <>
    struct type_to_char<char> {
      static constexpr const char str[] = "baz";
    };


    // main.cpp
    #include <iostream>
    #include <string>
    #include "types.h"

    constexpr const char type_to_char <char>::str[]; 

    int main() {
      std::cout << type_to_char<char>::str << std::endl;
    }

除非您提供静态constexpr数据成员的定义,否则不能使用它。
尝试使用odr-use时会发生以下情况:

std::cout << type_to_char<char>::str << std::endl;

这就是为什么需要定义的原因。
您可以轻松地重现此问题,如下所示:

struct S { static constexpr int x = 0; };
int main() { auto y = &S::x; (void)y; }

无论如何,在您的特定情况下,使用以下声明就足够了:

static constexpr char *str = "baz";

如果可以使用它而不是数组类型,则不必显式定义type_to_char<char>::str

暂无
暂无

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

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