c++ - 如何调用非模板方法而不是模板方法?

标签 c++

我有两个称为writeLine()的函数。我以为main()中的行会调用第一个writeLine(),但它会调用第二个writeLine()。如何调用第一个writeLine()函数?我只是很好奇,所以我稍后再知道是否可能。这是一个最小的示例:

#include <iostream> 
#include <cstdarg>

void writeLine(const char *format, ...)
{
    va_list args;
    va_start(args, format);
    vprintf(format, args);
}

template <typename Key, typename Value>
void writeLine(const Key &key, const Value &value, const char *separator = " ")
{
    std::cout << key << separator << value << std::endl;
}

int main()
{
    writeLine("%s is a test.", "This");

    return 0;
}

预期输出:“这是一个测试。”

当前输出:“%s是一个测试。这”

最佳答案

您可以将功能模板限制为不是char const *的类型,

template <typename Key, typename Value>
std::enable_if_t<std::negation_v<std::is_same<std::decay_t<Key> , char *>>, void>
  writeLine(const Key &key, const Value &value, const char *separator = " ")
{
    std::cout << key << separator << value << std::endl;
}

因此非模板功能是唯一的选择。

这是一个工作的demo

关于c++ - 如何调用非模板方法而不是模板方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61193745/

相关文章:

c++ - 在哪里为 tr1::array 添加重载运算符?

c++ - 引用变量的声明需要一个初始化器

c++ - "dynamic_cast"之后的 NULL 指针实际上可以取消引用吗?

c++ - 将 boost::depth_first_search 与访客一起使用

c++ - Allegro5 al_create_display() 在 Mac OS Catalina 上崩溃

c++ - sizeof(struct name_of_struct) 与 sizeof(name_of_struct) 的区别?

c++ - 如何避免为未使用的属性分配内存

c++ - 连接两个 move 的字符串

c++ - 如何在不知道成员类型的情况下检查 SFINAE 是否存在成员?

c++ - 运行 key 密码解密知道 key ?