gpt4 book ai didi

c++ - 在模板函数中自动将 const char[] 转换为 const char *

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:47:34 24 4
gpt4 key购买 nike

我在使用模板时遇到问题,如果您尝试为模板化函数提供字符串参数,编译器会将“Hello World”解释为 const char [12]。我希望它是 const char *。

我可以通过将每个字符串静态转换为“const char*”来“解决”这个问题,但由于我正在尝试将其用作日志系统的一部分,因此使它变得简单是一个很大的目标。

由于很难解释我的意思,我想出了一个简单的复制器。您会看到 main 函数的最后一行没有编译。

任何帮助将不胜感激

#include <string>

// Trivial base class so we can use polymorphism
class StoreItemsBase
{
public:
StoreItemsBase() {}
};

// Example of a trivial Templated class to hold some 3 items.
// Intent to have similar classes to hold 4,5..n items
template <typename T1, typename T2, typename T3>
class Store3Items : public StoreItemsBase
{
public:
Store3Items(const T1& t1, const T2& t2, const T3& t3)
:
StoreItemsBase(),
mT1(t1),
mT2(t2),
mT3(t3)
{}

private:
T1 mT1;
T2 mT2;
T3 mT3;
};

// Function to create a pointer to our object with added id
// There would be similar CreateHolderFunctions for 4,5..n items
template <typename T1, typename T2, typename T3>
StoreItemsBase* CreateHolder(const T1& t1, const T2& t2, const T3& t3)
{
return new Store3Items<T1, T2, T3>(t1, t2, t3);
}

int main()
{
int testInt=3;
double testDouble=23.4;
const std::string testStr("Hello World");

StoreItemsBase* Ok1 = CreateHolder(testInt, testDouble, testStr);
StoreItemsBase* Ok2 = CreateHolder(testDouble, testStr, testInt);
StoreItemsBase* Ok3 = CreateHolder(testStr, static_cast<const char*>("Hello there"), testInt);
// If you try a standard string, it compiler complains
// Although I could surround all my strings with the static cast, what I am looking for is a way
// to for the CreateHolder function to do the work for me
StoreItemsBase* NotOk4 = CreateHolder(testStr, "Hello World", testInt);

// Free our objects not shown in the example
}

编译器错误是:

example.cpp: In constructor ‘Store3Items::Store3Items(const T1&, const T2&, const T3&) [with T1 = std::basic_string, T2 = char [12], T3 = int]’:example.cpp:50:50:   instantiated from ‘StoreItemsBase* CreateHolder(const T1&, const T2&, const T3&) [with T1 = std::basic_string, T2 = char [12], T3 = int]’example.cpp:65:74:   instantiated from hereexample.cpp:21:11: error: array used as initializer

最佳答案

您可以使用元函数来转换作为参数传递给模板的类型。任何字符数组都将转换为 char* :

template< typename T > struct transform
{
typedef T type;
};

template< std::size_t N > struct transform< char[N] >
{
typedef char* type;
};
template< std::size_t N > struct transform< const char[N] >
{
typedef const char* type;
};

然后,而不是使用 Tn你可以直接使用 typename transform< Tn >::type .

更新:如果您使用C++11,那么std::decay已经做了你想要的。

关于c++ - 在模板函数中自动将 const char[] 转换为 const char *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10644979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com