Skip to content

Instantly share code, notes, and snippets.

@aligusnet
Last active May 31, 2020 10:27
Show Gist options
  • Save aligusnet/fb10c3d2c64b5ce68e88a2385c4d0397 to your computer and use it in GitHub Desktop.
Save aligusnet/fb10c3d2c64b5ce68e88a2385c4d0397 to your computer and use it in GitHub Desktop.
Logical C++
// alignas C++11, C++14
class alignas(32) Foo {...}
// address &foo is aligned to 32-byes boundary
Foo foo{};
// it is not guarantee that address pFoo is aligned to 32-byes boundary
Foo* pFoo = new Foo();
// there is no standard way to align heap-allocated addresses to a specific boundary in C++11 and C++14
// you can use C11 function aligned_alloc but C11 is not part of C++11/14 standards and therefore it is not portable
//////////////////////////////////////////////////////////////////////
// if constexpr in C++17
// the code below does not compile, because if constexpt instantiates code not dependent on template parameters even in else branch
#include <iostream>
template <typename T>
void test_print(T t)
{
if constexpr (std::is_integral_v<T>)
{
static_assert(sizeof(int)==1, "Hello from C++17");
}
std::cout << t << std::endl;
};
int main()
{
test_print(std::string("Hello World"));
}
// the code blow compiles necause static_assert depends on the template parameter T so the former one is eliminated
#include <iostream>
template <typename T>
void test_print(T t)
{
if constexpr (std::is_integral_v<T>)
{
static_assert(sizeof(T)==1, "Hello from C++17");
}
std::cout << t << std::endl;
};
int main()
{
test_print(std::string("Hello World"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment