3

使用 typeinfo 获取类名称,实现简单字符串模版参数,这种用法有什么弊端吗?

 2 years ago
source link: https://www.v2ex.com/t/817538
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  C++

使用 typeinfo 获取类名称,实现简单字符串模版参数,这种用法有什么弊端吗?

  sl0000 · 1 天前 · 612 次点击

#include <cxxabi.h>

template <typename T>
static inline const std::string classname() {
    int status;
    std::string actual_class_name = abi::__cxa_demangle(typeid(T).name(), 0, 0, &status);
    if (status != 0) {
        throw "Class " + std::string(typeid(T).name()) + " parse error";
    } else {
        return actual_class_name;
    }
}


template <typename T>
class kind {
    static inline const std::string n = classname<T>();
};

class dog { };
name<dog> d;

class cat { };
name<cat> c;

第 1 条附言  ·  22 小时 5 分钟前

@GeruzoniAnsasu c++2a 可以使用字符串模版

template<size_t N>
struct StringLiteral {
    
    constexpr StringLiteral(const char (&str)[N]) {
        std::copy_n(str, N, value);
    }
    
    char value[N];
};

template<StringLiteral lit>
void Print() {
    // The size of the string is available as a constant expression.
    constexpr auto size = sizeof(lit.value);
    // and so is the string's content.
    constexpr auto contents = lit.value;
    std::cout << "Size: " << size << ", Contents: " << contents << std::endl;
}

int main(int argc, const char * argv[]) {
    Print<"literal string">(); // Prints "Size: 15, Contents: literal string"
    return 0;
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK