C++ Logo


Advanced search

Allow use of constants and types from not-instantiation-ed template

From: Maciej Polanski <maciejpolanski75_at_[hidden]>
Date: Sun, 19 Dec 2021 20:35:07 +0100

So, let's just allow use of a types and static constants from
not-instantiation-ed template class (if possible):

   template<typename T>
   struct Foo{
       constexpr static int bar = 0x01;
   int i = Foo::bar; // Doesn't compile now, but could
   int j = Foo<class Nonexisting>::bar; // Ugly hack but works

This improvement should make template configuration behave similar to
class usages.
Classes frequently uses internal class constants, e.g.
"std::cout.setf(std::ios::hex, std::ios::basefield)".

So this change would allow to include constants and types used to
configure template, inside it.
Ideally, those should be visible inside template-initialization-list
without scope operators.

HelloWorld example:
#include <iostream>
// T needed for some functionality not listed here
template <typename T, int flags>
struct HelloWorld
     static constexpr int Hello = 0x1;
     static constexpr int World = 0x2;
     static constexpr int Exclamation = 0x4;
     void work(){
         if (flags & Hello)         // <- no code for this line
             std::cout << "Hello ";
         if (flags & World)         // <- no code for this line
             std::cout << "World";
         if (flags & Exclamation)   // <- no code for this line
             std::cout << "!\n";
int main()
     HelloWorld<int, Hello | World | Exclamation>{}.work(); // Prints 
"Hello World!"
     return 0;
Currently types and constants have to be defined before template, 
polluting higher scope. Or ugly hack used:
   HelloWorld<int, HelloWorld<void*, 0>::Hello | 
HelloWorld<std::iostream, -1>::World | HelloWorld<class Nonexisting, 
You can see this yourself in Compiler Explorer: 

Received on 2021-12-19 13:35:16