'type cast':无法从'T'转换为'const char *'

问题描述 投票:0回答:1

这是代码的相关部分: 它不允许我将 t 分配给我的 char arrayStringVal

#include <iostream>
#include <type_traits>
char arrayStringVal[6][20];
#define printf printDeveloperData

template <typename T>
void printDeveloperData(T t)
{

}

template<typename T, typename... Args>
void printDeveloperData(T& t, Args... args)
{
    strcpy(arrayStringVal[0], (const char*)t );// gives error here cannot convert from t to const char 
    printDeveloperData(args...);
}




int main()
{
    printf("z%d x%d f%d e%d", 22, 3, 11, 13);
    printf("z%d x%d f%s ", 53, 11, 13.1);

}


我希望找到一种方法将 t 的值赋给数组。 当然 t 可以是任何东西,但这只是真实代码中代码的相关部分 但是编译器 visual studio c++ 一直给我错误,t cannot cast to const char。 如果没有转换,它会给出错误 strcpy doesn't take t as a parameter.

我希望找到一种方法将 t 用于 strcpy

c++ templates typedef
1个回答
1
投票

你有两个问题:

  1. 你没有
    #include <cstring>
    ,所以编译器(可能)不知道
    strcpy
    是什么(取决于编译器头文件,它可能从你现有的
    #include
    s 之一获得定义)。
  2. 对于除第一个递归模板化调用之外的所有调用,作为
    t
    传递的值是一个
    int
    (在一种情况下,一个
    float
    ),而不是任何类型的类似字符串的东西。感谢它拒绝执行转换,如果它真的让你这样做,你将访问(几乎可以肯定)地址范围底部的未分配内存。

解决这个问题的非常不完整的尝试(因此一切都变成合法的字符串数据以从中复制)将是:

#include <cstring>
#include <iostream>
#include <type_traits>
char arrayStringVal[6][20];
#define printf printDeveloperData

template <typename T>
void printDeveloperData(T t)
{

}

template<typename T, typename... Args>
void printDeveloperData(T& t, Args... args)
{
    std::string tstr;
    if constexpr (std::is_array<T>::value || std::is_same<T, const char*>::value || std::is_same<T, std::string>::value) {
        tstr = t;
    } else {
        tstr = std::to_string(t); 
    }
    strcpy(arrayStringVal[0], tstr.data());// gives error here cannot convert from t to const char 
    printDeveloperData(args...);
}




int main()
{
    printf("z%d x%d f%d e%d", 22, 3, 11, 13);
    printf("z%d x%d f%s ", 53, 11, 13.1);

}

在线试用!

© www.soinside.com 2019 - 2024. All rights reserved.