【问题标题】:C++ convert string to typenameC ++将字符串转换为类型名
【发布时间】:2018-07-01 21:08:36
【问题描述】:

所以我发现各种文章和帖子说没有办法将typename 转换为string,但我还没有找到相反的。我有一个具有专业化功能的template

template <typename T>
void foo(T sth) {}

template <>
void foo<int>(int sth) {}
...

我正在从这样构造的文件中读取数据:

int 20
double 12.492
string word

有没有办法根据文件的内容调用foo() 的正确特化?

【问题讨论】:

  • 模板是编译时构造,你不能在运行时实例化或选择模板特化
  • if (std::compare(sType)=="string" {...} else if (std::compare(sType)=="int") {...}
  • 我明白了,我会编辑那个有意义的
  • "没有办法将 typename 转换为字符串" 也许没有标准的,但是有一些足够便携的,比如从@返回的字符串中取出名称987654328@.

标签: c++ templates typename


【解决方案1】:

是的,但它需要手动代码,并且您知道将出现在文件中的所有类型。这是因为模板是编译时构造,它们不能在运行时实例化。

如果您愿意,您可以随时使用预处理器或其他技巧来尝试减少样板文件。

void callFoo(std::string type, std::any arg) {
  if (type == "int")
      foo<int>(std::any_cast<int>(arg));
  else if (type == "double")
      foo<double>(std::any_cast<double>(arg));
  else if (type == "string")
      foo<std::string>(std::any_cast<std::string>(arg));
}

当然,这要求您传入正确的类型(没有隐式转换!)。我看不出有什么办法可以避免这种情况。

【讨论】:

  • 谢谢你的回答,对我来说看起来不错,不过我会把问题留待其他答案
  • @koman 哦,是的,请这样做。我也想知道是否有比我更清洁的解决方案:)
【解决方案2】:

说实话,我不确定是否理解您的问题。正如我所解释的那样,我相信您在运行时不需要一种调度程序,也不需要计算包含类型名称的字符串。只需编写一个通用模板函数,该函数调用一个特殊的模板包装器,根据类型消除对foo() 的调用。您需要专门的 foo() 接收第二个特殊参数 (the_type&lt;T&gt;),用于消除歧义。

这里有一个完整的操作演示:

# include <string>
# include <iostream>

using namespace std;

template<class T> struct the_type { using type = T; };

template <typename T>
void foo(const T par)
{
  foo(par, the_type<T>());
}

void foo(int par, the_type<int>)
{
  cout << "int " << par << endl;
}

void foo(double par, the_type<double>)
{
  cout << "double " << par << endl;
}

void foo(const string & par, the_type<string>)
{
  cout << "string " << par << endl;
}

void foo(const char * par, the_type<const char*>)
{
  cout << "char* " << par << endl;
}    

int main()
{
  foo(20);
  foo(12.492);
  foo("word");
  foo(string("word"));
}

谁的输出是:

int 20
double 12.492
char* word
string word

如果您需要其他专业,那么您只需定义它。在某些情况下,您必须将特化显式定义为模板参数。

您可以使用宏操作符来避免重复的事情。例如,假设foo() 结构相同,您可以将其封装在宏中。像这样的:

# define GENFOO(type_name)                      \
  void foo(type_name par, the_type<type_name>)  \
  {                                             \
    cout << #type_name " " << par << endl;      \
  }

GENFOO(int);
GENFOO(double);
GENFOO(string)

但是,我想说foo() 的每个特殊版本都不会那么相似。

【讨论】:

    猜你喜欢
    • 2023-02-08
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多