Concatenate compile-time strings in a template at compile time?

前端 未结 3 1703
猫巷女王i
猫巷女王i 2020-12-08 12:47

Currently I have:

template  struct typename_struct {
    static char const* name() { 
        return (std::string(typename_struc         


        
3条回答
  •  再見小時候
    2020-12-08 13:04

    I'm not sure of what you're searching for but I believe you're interested in a combination of typeid and name-demangling (which compiler are you using?)

    In gcc it would be something like

    #include
    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    std::string demangle(const char* name) {
        int status = -4; // some arbitrary value to eliminate the compiler warning
    
        // enable c++11 by passing the flag -std=c++11 to g++
        std::unique_ptr res {
            abi::__cxa_demangle(name, NULL, NULL, &status),
            std::free
        };
        return (status==0) ? res.get() : name ;
    }
    
    template  struct typename_struct {
      static std::string name() {
        std::string typeName = typeid(T).name();
        return demangle(typeName.c_str());
      }
    };
    
    int main(){
    
      cout << typename_struct::name(); // Prints "int****"
    
      return 0;
    }
    

    http://ideone.com/nLsFF0

    Sources: https://stackoverflow.com/a/4541470/1938163

    As for your question: those aren't constexpr constructs, thus the evaluation happens at runtime although the templated parameters and code are instantiated at compile-time.

    Using templates doesn't mean every instruction contained in there will be executed and resolved at "compile-time".

    I believe you can't achieve this whole bunch of stuff at compile-time since there are de-mangling functions (ABI-specific) involved. If I interpreted your question wrong please let me know.

提交回复
热议问题